<template>
    <div class="amap-container">
        <!-- 地图容器 -->
        <div id="amap-view" :style="{ display: mapType !== 'roadmap' ? 'block' : 'none' }" class="amap-view"
            ref="mapContainer"></div>
        <template v-if="mapType == 'roadmap'">
            <CesiumTemplate :active-filter="activeFilter" :key="mapType" @poi-selected="handleCesiumPoiSelected"
                @stats-updated="updateStats" ref="cesiumMapRef" />
        </template>

        <!-- 巡检模式组件 -->
        <template v-if="mapMode === 'patrol'">
            <PatrolRoute :map-instance="map" :is-visible="mapMode === 'patrol'"
                @route-selected="handlePatrolRouteSelected" @patrol-started="handlePatrolStarted"
                @patrol-stopped="handlePatrolStopped" @waypoint-reached="handleWaypointReached" />
        </template>

        <!-- 热力图组件 -->
        <HeatMap v-if="map" :map="map" :enabled="heatmapEnabled"
            :visible="mapMode !== 'patrol' && mapType !== 'roadmap'" @heatmap-created="handleHeatmapCreated"
            @heatmap-removed="handleHeatmapRemoved" />
        <!-- 地图控制面板 -->
        <div class="map-controls">
            <div class="view-controls">
                <button class="control-btn" :class="{ active: mapType === 'roadmap' && mapMode !== 'patrol' }"
                    @click="switchMapType('roadmap')" title="标准地图">
                    <svg viewBox="0 0 24 24">
                        <path
                            d="M20.5,3L20.34,3.03L15,5.1L9,3L3.36,4.9C3.15,4.97 3,5.15 3,5.38V20.5A0.5,0.5 0 0,0 3.5,21L3.66,20.97L9,18.9L15,21L20.64,19.1C20.85,19.03 21,18.85 21,18.62V3.5A0.5,0.5 0 0,0 20.5,3Z"
                            fill="currentColor" />
                    </svg>
                    <span>3D</span>
                </button>
                <button class="control-btn" :class="{ active: mapMode === 'patrol' }" @click="switchMapMode('patrol')"
                    title="巡检模式">
                    <svg viewBox="0 0 24 24">
                        <path
                            d="M12,2A2,2 0 0,1 14,4V8A2,2 0 0,1 12,10A2,2 0 0,1 10,8V4A2,2 0 0,1 12,2M21,9V7L15,1L13.5,2.5L16.17,5.17L10.59,10.75C10.21,10.59 9.8,10.5 9.37,10.5A6,6 0 0,0 3.37,16.5C3.37,19.24 5.62,21.5 8.37,21.5A6,6 0 0,0 14.37,15.5C14.37,15.07 14.28,14.66 14.12,14.28L19.7,8.7L22.37,11.37L23.87,9.87L21.37,7.37Z"
                            fill="currentColor" />
                    </svg>
                    <span>巡检</span>
                </button>
                <button class="control-btn" :class="{ active: mapType === 'satellite' && mapMode !== 'patrol' }"
                    @click="switchMapType('satellite')" title="卫星图">
                    <svg viewBox="0 0 24 24">
                        <path
                            d="M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17Z"
                            fill="currentColor" />
                    </svg>
                    <span>卫星图</span>
                </button>

                <button class="control-btn" @click="resetView" title="重置视角">
                    <svg viewBox="0 0 24 24">
                        <path
                            d="M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M18,11H13L14.5,9.5L12.5,7.5L11,9H6V11H11L9.5,12.5L11.5,14.5L13,13H18V11Z"
                            fill="currentColor" />
                    </svg>
                    <span>重置</span>
                </button>
                <button class="control-btn"
                    :class="{ active: heatmapEnabled, disabled: mapMode === 'patrol' || mapType === 'roadmap' }"
                    @click="toggleHeatmap" title="热力图" :disabled="mapMode === 'patrol' || mapType === 'roadmap'">
                    <svg viewBox="0 0 24 24">
                        <path
                            d="M11.71,19C9.93,19 8.5,17.59 8.5,15.86C8.5,14.24 9.53,13.1 11.3,12.74C13.07,12.38 14.9,11.53 15.92,10.16C16.31,11.45 16.5,12.81 16.5,14.2C16.5,16.84 14.36,19 11.71,19M13.5,0.67C13.5,0.67 14.24,3.32 14.24,5.47C14.24,7.53 12.89,9.2 10.83,9.2C8.76,9.2 7.2,7.53 7.2,5.47L7.23,5.1C7.41,4.84 7.79,4.23 8.55,3.29C9.36,2.26 10.51,0.67 13.5,0.67M5.08,11.17C5.08,11.17 6.09,12.96 6.09,14.25C6.09,15.54 5.08,16.58 3.79,16.58C2.5,16.58 1.46,15.54 1.46,14.25C1.46,12.96 2.5,11.17 5.08,11.17M9.5,22.5C9.5,22.5 10.47,20.83 10.47,19.58C10.47,18.33 9.5,17.36 8.25,17.36C7,17.36 6.03,18.33 6.03,19.58C6.03,20.83 7,22.5 9.5,22.5Z"
                            fill="currentColor" />
                    </svg>
                    <span>热力图</span>
                </button>
            </div>

            <!-- POI类型筛选 - 暂时注释 -->
            <!-- 
            <div class="poi-filter">
                <h4>POI类型筛选</h4>
                <div class="filter-buttons">
                    <button class="filter-btn" :class="{ active: activeFilter === 'all' }" @click="filterPois('all')">
                        全部({{ getTotalPois() }})
                    </button>
                    <button class="filter-btn" :class="{ active: activeFilter === 'scenic' }"
                        @click="filterPois('scenic')">
                        景点({{ getPoiCount('scenic') }})
                    </button>
                    <button class="filter-btn" :class="{ active: activeFilter === 'monitor' }"
                        @click="filterPois('monitor')">
                        监控({{ getPoiCount('monitor') }})
                    </button>
                    <button class="filter-btn" :class="{ active: activeFilter === 'service' }"
                        @click="filterPois('service')">
                        服务({{ getPoiCount('service') }})
                    </button>
                    <button class="filter-btn" :class="{ active: activeFilter === 'dining' }"
                        @click="filterPois('dining')">
                        餐饮({{ getPoiCount('dining') }})
                    </button>
                </div>
            </div>
            -->
        </div>

        <!-- 实时统计信息 -->
        <div class="stats-panel" :class="{ 'patrol-mode': mapMode === 'patrol' }">
            <div class="stat-item">
                <span class="stat-value">{{ stats.totalVisitors }}</span>
                <span class="stat-label">实时在园</span>
            </div>
            <div class="stat-item">
                <span class="stat-value">{{ visiblePois.length }}</span>
                <span class="stat-label">显示POI</span>
            </div>
            <div class="stat-item">
                <span class="stat-value">{{ stats.alertCount }}</span>
                <span class="stat-label">预警信息</span>
            </div>
        </div>

        <!-- POI详情信息窗 - 只在2D模式下显示 -->
        <div v-if="selectedPoi && mapType !== 'roadmap'" class="poi-detail-panel" :style="detailPanelStyle">
            <div class="detail-header">
                <h3>{{ selectedPoi.name }}</h3>
                <button class="close-btn" @click="closePoiDetail">×</button>
            </div>
            <div class="detail-content">
                <div class="poi-info">
                    <div class="info-row">
                        <span class="label">类型:</span>
                        <span class="value">{{ selectedPoi.typeName }}</span>
                    </div>
                    <div class="info-row">
                        <span class="label">状态:</span>
                        <span class="value" :class="selectedPoi.status">{{ selectedPoi.status === 'active' ? '正常' : '异常'
                            }}</span>
                    </div>
                    <div v-if="selectedPoi.type === 'scenic'" class="scenic-details">
                        <div class="info-row">
                            <span class="label">当前游客:</span>
                            <span class="value">{{ selectedPoi.data.currentVisitors }}/{{ selectedPoi.data.capacity
                                }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">温度:</span>
                            <span class="value">{{ selectedPoi.data.temperature }}°C</span>
                        </div>
                    </div>
                    <div v-else-if="selectedPoi.type === 'monitor'" class="monitor-details">
                        <div class="info-row">
                            <span class="label">设备类型:</span>
                            <span class="value">{{ selectedPoi.data.deviceType }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">分辨率:</span>
                            <span class="value">{{ selectedPoi.data.resolution }}</span>
                        </div>
                        <button v-if="selectedPoi.data.videoUrl" class="video-btn" @click="openVideo">
                            📹 查看监控视频
                        </button>
                    </div>
                    <div v-else-if="selectedPoi.type === 'entrance'" class="entrance-details">
                        <div class="info-row">
                            <span class="label">日通行量:</span>
                            <span class="value">{{ selectedPoi.data.dailyTraffic }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">当前流量:</span>
                            <span class="value">{{ selectedPoi.data.currentFlow }}</span>
                        </div>
                    </div>
                </div>
                <div class="poi-description">
                    <p>{{ selectedPoi.data.description }}</p>
                </div>
            </div>
        </div>

    </div>
    <!-- 景区选择 -->
    <div class="scenic-select" @click="selectClick">
        <div class="selected-option">
            {{ selectedScenicLabel }}
            <svg class="arrow-icon" viewBox="0 0 24 24">
                <path d="M7 10l5 5 5-5z" fill="currentColor" />
            </svg>
        </div>
        <div class="scenic-select-options" v-show="scenicAreaCfg.isSelectOpen">
            <div v-for="item in scenicAreaCfg.opts" :key="item.id" class="scenic-select-option"
                :class="{ selected: scenicAreaCfg.value == item.id }" @click.stop="handleCustomSelect(item)">
                {{ item.label }}
            </div>
        </div>
    </div>
    <!-- 监控视频弹窗 - 使用Teleport渲染到body -->
    <Teleport to="body">
        <div v-if="showMonitorVideo" class="monitor-video-modal">
            <div class="video-modal-overlay" @click="closeMonitorVideo"></div>
            <div class="video-modal-content">
                <div class="video-header">
                    <h3>{{ selectedPoi?.name || '监控画面' }}</h3>
                    <button class="video-close-btn" @click="closeMonitorVideo">×</button>
                </div>
                <div class="video-container">
                    <video ref="videoPlayerRef" :src="currentVideoSource" controls autoplay muted class="monitor-video"
                        @loadstart="() => console.log('视频开始加载')" @error="(e) => console.error('视频加载错误:', e)">
                        您的浏览器不支持视频播放
                    </video>
                </div>
                <div class="video-info" v-if="selectedPoi">
                    <div class="info-item">
                        <span class="label">设备类型:</span>
                        <span class="value">{{ selectedPoi.data?.deviceType || '高清摄像头' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">分辨率:</span>
                        <span class="value">{{ selectedPoi.data?.resolution || '1080P' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">位置:</span>
                        <span class="value">{{ selectedPoi.data?.address || selectedPoi.name }}</span>
                    </div>
                </div>
            </div>
        </div>
    </Teleport>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch, Teleport, reactive, nextTick } from 'vue'
import CesiumTemplate from './CesiumTemplate.vue'
import PatrolRoute from './PatrolRoute.vue'
import HeatMap from './HeatMap.vue'
import { getPoiTypeInfo, getMonitorVideoSource } from './amapPoiTypes.js'

import useDataStore from '@/stores/data.js';
import { storeToRefs } from 'pinia';
const store = useDataStore();
const { amapPoiData, listTypes, patrolPlans } = storeToRefs(store)
import api from '@/api'

// Props
const props = defineProps({
    activeType: {
        type: [String, Number],
        default: 'all'
    }
})

// Emits
const emit = defineEmits([
    'poi-selected',
    'stats-updated',
    'patrol-started',
    'patrol-stopped',
    'waypoint-reached'
])

// 响应式数据
const mapContainer = ref(null)
const cesiumMapRef = ref(null);
const map = ref(null)
const mapType = ref('satellite') // 卫星图satellite, 3d地图roadmap
const mapMode = ref('normal') // 地图模式：普通 normal, 热力图 patrol
const activeFilter = ref('all') // 默认显示全部POI
const selectedPoi = ref(null)
const heatmapEnabled = ref(false) // 热力图开关状态
const defaultStates = ref({
    satellite: {
        center: [105.58804, 30.516691],
        zoom: 15.4,
        mapStyle: 'amap://styles/satellite'
    },
    roadmap: {
        center: [105.58804, 30.516691],
        zoom: 15.4,
        mapStyle: 'amap://styles/normal'
    },
    patrol: {
        center: [105.58804, 30.516691],
        zoom: 15.4,
        mapStyle: 'amap://styles/satellite'
    }
})
const scenicAreaCfg = reactive({
    opts: [
        {
            label: '圣莲岛',
            id: 1,
            position: [105.5855290169053, 30.515235578496224, 5200],
            url: "https://xxgtjc.tgmis.cn:1000/file/models/sld/terra_b3dms/tileset.json",
            zoom: 15.4,
        },
        {
            label: '圣平岛',
            id: 2,
            position: [105.6243171482977, 30.490070111736895, 4200],
            url: "https://xxgtjc.tgmis.cn:1000/file/models/spd_hd/terra_b3dms/tileset.json",
            zoom: 15.4,
        },
        {
            label: '九连洲',
            id: 3,
            position: [105.57007791695878, 30.535412615617478, 2200],
            url: "https://xxgtjc.tgmis.cn:1000/file/models/jlz_hd/terra_b3dms/tileset.json",
            zoom: 15.4,
        },
    ],
    value: 1,
    isSelectOpen: false,
})

const selectedScenicLabel = computed(() => {
    return scenicAreaCfg.opts.find(item => item.id === scenicAreaCfg.value)?.label || '请选择'
})

const detailPanelStyle = ref({})
const showMonitorVideo = ref(false)
const currentVideoSource = ref('')
const videoPlayerRef = ref(null)

// 地图相关对象
let markers = []
let infoWindow = null

// 统计数据
const stats = ref({
    totalVisitors: 2568,
    alertCount: amapPoiData.value.filter(poi => poi.isAlert).length
})

// 坐标转换相关常量
const PI = Math.PI
const x_PI = PI * 3000.0 / 180.0
const a = 6378245.0
const ee = 0.00669342162296594323

/**
 * 判断是否在中国境内
 * @param lng 经度
 * @param lat 纬度
 * @returns {boolean}
 */
const outOfChina = (lng, lat) => {
    return (lng < 72.004 || lng > 137.8347) || (lat < 0.8293 || lat > 55.8271)
}

/**
 * 转换纬度
 * @param lng 经度
 * @param lat 纬度
 * @returns {number}
 */
const transformLat = (lng, lat) => {
    let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng))
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
    ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0
    ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0
    return ret
}

/**
 * 转换经度
 * @param lng 经度
 * @param lat 纬度
 * @returns {number}
 */
const transformLng = (lng, lat) => {
    let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
    ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
    ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0
    ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0
    return ret
}

/**
 * WGS84转GCJ02坐标系（GPS坐标转高德地图坐标）
 * @param lng 经度
 * @param lat 纬度
 * @returns {Array} [转换后经度, 转换后纬度]
 */
const wgs84ToGcj02 = (lng, lat) => {
    if (outOfChina(lng, lat)) {
        return [lng, lat]
    }

    let dlat = transformLat(lng - 105.0, lat - 35.0)
    let dlng = transformLng(lng - 105.0, lat - 35.0)

    const radlat = lat / 180.0 * PI
    let magic = Math.sin(radlat)
    magic = 1 - ee * magic * magic
    const sqrtmagic = Math.sqrt(magic)
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI)
    dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI)

    const mglat = lat + dlat
    const mglng = lng + dlng

    return [mglng, mglat]
}

/**
 * 转换POI坐标（从天地图坐标系转换为高德地图坐标系）
 * @param coordinates 原始坐标对象 {lng, lat}
 * @returns {Object} 转换后的坐标对象 {lng, lat}
 */
const convertPoiCoordinates = (coordinates) => {
    const [convertedLng, convertedLat] = wgs84ToGcj02(coordinates.lng, coordinates.lat)
    return {
        lng: convertedLng,
        lat: convertedLat
    }
}

// 计算可见POI
const visiblePois = computed(() => {
    if (activeFilter.value == 'all') {
        return amapPoiData.value
    }
    return amapPoiData.value.filter(poi => poi.type == activeFilter.value)
})

// 获取POI类型标签
const getPoiTypeLabel = (type) => {
    if (listTypes.value[type] && listTypes.value[type].name) {
        return listTypes.value[type].name
    } else {
        return '其他'
    }
}

// 获取POI数量
const getPoiCount = (type) => {
    return amapPoiData.value.filter(poi => poi.type === type).length
}

const getTotalPois = () => {
    return amapPoiData.value.length
}

// 初始化高德地图
const initAmapMap = () => {
    if (!window.AMap) {
        console.error('高德地图API未加载')
        return
    }

    // 设置地图中心坐标（天地图坐标转换为高德地图坐标）
    const centerCoordinates = wgs84ToGcj02(105.58804, 30.516691)

    // 创建地图实例
    map.value = new AMap.Map('amap-view', {
        center: centerCoordinates, // 转换后的中心坐标
        zoom: 15.4,
        mapStyle: 'amap://styles/dark', // 使用深色样式作为基础
        features: ['bg', 'road', 'building', 'point'],
        viewMode: '2D'
    })

    // 创建信息窗体
    infoWindow = new AMap.InfoWindow({
        isCustom: false,
        content: '',
        offset: new AMap.Pixel(0, -30)
    })

    // 加载POI标记
    loadPoiMarkers()

    // 添加地图事件监听
    map.value.on('click', () => {
        closePoiDetail()
    })

}

// 加载POI标记
const loadPoiMarkers = () => {
    // 先清除现有标记
    clearMarkers()

    // 3D模式、巡检模式或热力图模式下不显示POI标记
    if (mapType.value === 'roadmap' || mapMode.value === 'patrol' || heatmapEnabled.value) {
        console.log('当前模式不显示POI标记:', { mapType: mapType.value, mapMode: mapMode.value, heatmapEnabled: heatmapEnabled.value })
        return
    }

    // 确保地图对象存在
    if (!map.value) {
        console.warn('地图对象不存在，无法加载POI标记')
        return
    }


    try {
        let loadedCount = 0
        visiblePois.value.forEach((poi, index) => {
            try {
                createPoiMarker(poi)
                loadedCount++
            } catch (error) {
                console.error(`创建POI标记失败 [${index}]:`, poi.name, error)
            }
        })
    } catch (error) {
        console.error('POI标记加载过程出错:', error)
    }
}

// 创建POI标记
const createPoiMarker = (poi) => {
    if (!poi || !poi.coordinates) {
        console.warn('POI数据无效:', poi)
        return
    }

    try {
        // 转换坐标：从天地图坐标系转换为高德地图坐标系
        const convertedCoordinates = convertPoiCoordinates(poi.coordinates)

        if (!convertedCoordinates || isNaN(convertedCoordinates.lng) || isNaN(convertedCoordinates.lat)) {
            console.warn('POI坐标转换失败:', poi.name, poi.coordinates)
            return
        }

        // 根据POI类型设置图标
        const iconConfig = getPoiIcon(poi.type, poi.isAlert)

        if (!iconConfig || !iconConfig.icon) {
            console.warn('POI图标配置失败:', poi.name, poi.type)
            return
        }

        const marker = new AMap.Marker({
            position: [convertedCoordinates.lng, convertedCoordinates.lat],
            icon: iconConfig.icon,
            offset: new AMap.Pixel(-12, -24),
            title: poi.name,
            extData: { ...poi, convertedCoordinates } // 保存转换后的坐标
        })

        // 添加点击事件
        marker.on('click', (e) => {
            try {
                const poiData = e.target.getExtData()
                showPoiDetail(poiData, e)
            } catch (error) {
                console.error('POI点击事件错误:', error)
            }
        })

        // 添加悬停效果
        marker.on('mouseover', (e) => {
            try {
                const poiData = e.target.getExtData()
                showPoiTooltip(poiData, e)
            } catch (error) {
                console.error('POI悬停事件错误:', error)
            }
        })

        marker.on('mouseout', () => {
            try {
                if (infoWindow) {
                    infoWindow.close()
                }
            } catch (error) {
                console.error('POI鼠标移出事件错误:', error)
            }
        })

        if (map.value) {
            map.value.add(marker)
            markers.push(marker)
        } else {
            console.warn('地图对象不存在，无法添加POI标记:', poi.name)
        }
    } catch (error) {
        console.error('创建POI标记失败:', poi.name, error)
    }
}

// 获取POI图标配置
const getPoiIcon = (type, isAlert) => {
    const iconSize = isAlert ? [28, 28] : [24, 24]
    const iconColor = isAlert ? '#ff4444' : getTypeColor(type)

    // 创建自定义图标
    const iconUrl = createIconSvg(type, iconColor, isAlert)

    return {
        icon: new AMap.Icon({
            image: iconUrl,
            size: new AMap.Size(iconSize[0], iconSize[1]),
            imageSize: new AMap.Size(iconSize[0], iconSize[1])
        })
    }
}

// 创建SVG图标
const createIconSvg = (type, color, isAlert) => {
    const iconConfigs = {
        scenic: 'M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z',
        monitor: 'M4,6H20V16H4M20,18A2,2 0 0,0 22,16V6C22,4.89 21.1,4 20,4H4C2.89,4 2,4.89 2,6V16A2,2 0 0,0 4,18H10V20H8V22H16V20H14V18H20Z',
        entrance: 'M22,16V4A2,2 0 0,0 20,2H8A2,2 0 0,0 6,4V16A2,2 0 0,0 8,18H20A2,2 0 0,0 22,16M16,5H19V8H16V5M16,9H19V12H16V9M16,13H19V16H16V13M8,5H15V8H8V5M8,9H15V12H8V9M8,13H15V16H8V13M2,20V22H4V20H2M6,20V22H20V20H6Z',
        accommodation: 'M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z',
        dining: 'M11,9H13V22H11V9M9,10A1,1 0 0,0 8,11V15A1,1 0 0,0 9,16H11V10H9M20,10H17V16A1,1 0 0,0 18,17H19A1,1 0 0,0 20,16V10M16,10A1,1 0 0,0 15,11V15A1,1 0 0,0 16,16H18V10H16M7,2V9H8V22H10V2H7Z',
        service: 'M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M11,14H13V20H11V14M11,4H13V12H11V4Z',
        shopping: 'M17,18C17.56,18 18,18.44 18,19C18,19.56 17.56,20 17,20C16.44,20 16,19.56 16,19C16,18.44 16.44,18 17,18M1,2V4H3L6.6,11.59L5.24,14.04C5.09,14.32 5,14.65 5,15A2,2 0 0,0 7,17H19V15H7.42A0.25,0.25 0 0,1 7.17,14.75C7.17,14.7 7.18,14.66 7.2,14.63L8.1,13H15.55C16.3,13 16.96,12.58 17.3,11.97L20.88,5H5.21L4.27,2H1M7,18C7.56,18 8,18.44 8,19C8,19.56 7.56,20 7,20C6.44,20 6,19.56 6,19C6,18.44 6.44,18 7,18Z'
    }

    const path = iconConfigs[type] || iconConfigs.scenic
    const size = 24

    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
      <defs>
        <filter id="shadow-${type}" x="-20%" y="-20%" width="140%" height="140%">
          <feDropShadow dx="1" dy="1" stdDeviation="2" flood-opacity="0.3"/>
        </filter>
        ${isAlert ? `
        <circle id="pulse-${type}" cx="${size / 2}" cy="${size / 2}" r="${size / 2 - 3}" fill="none" stroke="#ff0000" stroke-width="2" opacity="0.8">
          <animate attributeName="r" values="${size / 2 - 3};${size / 2 + 2};${size / 2 - 3}" dur="2s" repeatCount="indefinite"/>
          <animate attributeName="opacity" values="0.8;0.3;0.8" dur="2s" repeatCount="indefinite"/>
        </circle>
        ` : ''}
      </defs>
      
      <!-- 背景圆形 -->
      <circle cx="${size / 2}" cy="${size / 2}" r="${size / 2 - 2}" 
              fill="${color}" 
              stroke="#ffffff" 
              stroke-width="2" 
              filter="url(#shadow-${type})"/>
      
      ${isAlert ? `<use href="#pulse-${type}"/>` : ''}
      
      <!-- 图标路径 -->
      <g transform="translate(${(size - 16) / 2}, ${(size - 16) / 2}) scale(0.67)">
        <path d="${path}" fill="#ffffff" />
      </g>
    </svg>
  `

    return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg)
}

// 获取类型颜色
const getTypeColor = (type) => {
    const colors = {
        scenic: '#52b788',      // 景点 - 主墨绿色
        monitor: '#74c69d',     // 监控 - 浅墨绿色 
        entrance: '#40916c',    // 出入口 - 深墨绿色
        accommodation: '#95d5b2', // 住宿 - 最浅墨绿色
        dining: '#2d6a4f',      // 餐饮 - 中等墨绿色
        service: '#6a994e',     // 服务 - 橄榄绿
        shopping: '#a7c957'     // 购物 - 草绿色
    }
    return colors[type] || '#52b788'
}

// 显示POI详情
const showPoiDetail = (poi, event) => {
    selectedPoi.value = poi

    // 如果是监控POI，显示视频弹窗
    if (poi.type === 'monitor') {
        const videoSource = getMonitorVideoSource(poi.id)
        if (videoSource) {
            currentVideoSource.value = videoSource
            showMonitorVideo.value = true

            // 防止页面滚动
            document.body.style.overflow = 'hidden'

            return // 监控POI只显示视频弹窗，不显示普通详情面板
        }
    }

    // 使用转换后的坐标计算面板位置
    const coordinates = poi.convertedCoordinates || convertPoiCoordinates(poi.coordinates)
    const pixel = map.value.lngLatToContainer(new AMap.LngLat(coordinates.lng, coordinates.lat))
    detailPanelStyle.value = {
        position: 'absolute',
        left: `${pixel.x + 20}px`,
        top: `${pixel.y - 10}px`,
        zIndex: 1000
    }

    emit('poi-selected', poi)
}

// 显示POI提示信息
const showPoiTooltip = (poi, event) => {
    const content = `
    <div style="padding: 8px; min-width: 150px;">
      <h4 style="margin: 0 0 5px 0; color: #333;">${poi.name}</h4>
      <p style="margin: 0; color: #666; font-size: 12px;">${poi.typeName}</p>
      ${poi.isAlert ? '<p style="margin: 5px 0 0 0; color: #ff4444; font-size: 12px;">⚠️ 有预警信息</p>' : ''}
    </div>
  `

    // 使用转换后的坐标显示提示框
    const coordinates = poi.convertedCoordinates || convertPoiCoordinates(poi.coordinates)
    infoWindow.setContent(content)
    infoWindow.open(map.value, [coordinates.lng, coordinates.lat])
}

// 关闭POI详情
const closePoiDetail = () => {
    selectedPoi.value = null
    infoWindow.close()
}

// 关闭监控视频弹窗
const closeMonitorVideo = () => {
    showMonitorVideo.value = false
    currentVideoSource.value = ''

    // 暂停视频播放
    if (videoPlayerRef.value) {
        videoPlayerRef.value.pause()
    }

    // 恢复页面滚动
    document.body.style.overflow = ''
}

// 切换地图类型
const switchMapType = (type) => {
    resetView()
    // 如果点击的是当前已激活的地图类型且不在巡检模式，则不做任何操作
    if (mapType.value === type && mapMode.value !== 'patrol') return

    // 退出巡检模式，进入普通地图模式
    mapMode.value = 'normal'
    const oldMapType = mapType.value
    mapType.value = type

    // 切换地图时清除选中的POI状态
    selectedPoi.value = null
    closePoiDetail()

    if (type === 'roadmap') {
        // 切换到3D模式时清除2D地图的POI标记
        scenicAreaCfg.value = 1;
        clearMarkers()
        return
    }

    if (map.value) {
        try {
            if (type === 'satellite') {
                // 先设置为标准卫星图
                map.value.setMapStyle('amap://styles/satellite')
            } else {
                // 切换到标准地图
                map.value.setMapStyle('amap://styles/normal')
            }

            // 重新加载POI标记（延迟执行，确保地图样式切换完成）
            setTimeout(() => {
                loadPoiMarkers()
            }, 300)

        } catch (error) {
            console.error('地图样式切换失败:', error)
            // 发生错误时回滚到之前的地图类型
            mapType.value = oldMapType
        }
    }
}

// 切换地图模式（巡检/普通）
const switchMapMode = (mode) => {
    // 清除当前选中的POI
    selectedPoi.value = null
    closePoiDetail()

    if (mode === 'patrol') {
        mapMode.value = 'patrol'
        // 清除POI标记
        clearMarkers()

        // 巡检模式使用卫星图作为基础图层，但不更改mapType状态
        if (!mapType.value || mapType.value === 'roadmap') {
            mapType.value = 'satellite' // 如果当前是3D模式，切换到卫星图
        }

        // 设置卫星图样式以适合巡检路线展示
        if (map.value) {
            map.value.setMapStyle('amap://styles/satellite')
            // 调整地图视角以适合巡检路线展示
            const centerCoordinates = wgs84ToGcj02(105.58804, 30.516691)
            map.value.setZoomAndCenter(15.6, centerCoordinates)
        }
    } else {
        mapMode.value = 'normal'
        // 恢复到普通地图模式，重新应用当前地图类型的样式
        switchMapType(mapType.value)
        // 重新加载POI标记（会自动检查热力图状态）
        loadPoiMarkers()
    }
}

// 重置视角 - 增强版，支持不同模式的默认状态
const resetView = () => {
    if (!map.value) return

    let targetState = scenicAreaCfg.opts.find(item => item.id == scenicAreaCfg.value)

    // 转换坐标并重置视角
    const centerCoordinates = wgs84ToGcj02(targetState.position[0], targetState.position[1])
    map.value.setZoomAndCenter(targetState.zoom, centerCoordinates)

    // // 如果不是3D模式，重置地图样式
    // if (mapType.value !== 'roadmap') {
    //     map.value.setMapStyle(targetState.mapStyle)
    // }

    // 清除选中状态
    selectedPoi.value = null
    closePoiDetail()

    // 重置过滤器
    if (mapMode.value !== 'patrol') {
        activeFilter.value = 'all'
    }
}

// 巡检相关事件处理
const handlePatrolRouteSelected = (route) => {
    console.log('选择巡检路线:', route)
    // 这里可以添加额外的路线选择处理逻辑
}

const handlePatrolStarted = (data) => {
    console.log('巡检开始:', data)
    emit('patrol-started', data)
    // 可以更新统计信息或发送通知
}

const handlePatrolStopped = (state) => {
    console.log('巡检结束:', state)
    emit('patrol-stopped', state)
    // 可以生成巡检报告或保存巡检记录
}

const handleWaypointReached = (waypoint) => {
    console.log('到达检查点:', waypoint)
    emit('waypoint-reached', waypoint)
    // 可以触发检查点相关的操作，如拍照、记录等
}

// 切换热力图
const toggleHeatmap = () => {
    // 巡检模式和3D模式下不允许切换热力图
    if (mapMode.value === 'patrol' || mapType.value === 'roadmap') {
        return
    }

    heatmapEnabled.value = !heatmapEnabled.value
}

// 热力图创建成功回调
const handleHeatmapCreated = (data) => {
    console.log('热力图已创建，数据点数量:', data.dataPoints, '最大值:', data.maxValue)
}

// 热力图移除回调
const handleHeatmapRemoved = () => {
    console.log('热力图已移除')
}

// 过滤POI
const filterPois = (type) => {
    activeFilter.value = type
    loadPoiMarkers()

    // 更新统计
    stats.value.alertCount = visiblePois.value.filter(poi => poi.isAlert).length
    emit('stats-updated', stats.value)
}

// 清除所有标记
const clearMarkers = () => {
    if (markers.length > 0) {
        map.value.remove(markers)
        markers = []
    }
}

// 打开视频
const openVideo = () => {
    if (selectedPoi.value?.data?.videoUrl) {
        // 这里可以集成视频播放器
        alert(`打开监控视频: ${selectedPoi.value.data.videoUrl}`)
    }
}

// 更新统计数据
const updateStats = (newStats) => {
    Object.assign(stats.value, newStats)
}

// 处理Cesium POI选中事件
const handleCesiumPoiSelected = (poi) => {
    // 在3D模式下不使用AmapView的POI详情面板
    // CesiumTemplate会处理自己的提示框显示
    emit('poi-selected', poi)
}


// 监听外部属性变化
watch(() => props.activeType, (newType) => {
    if (newType !== activeFilter.value) {
        filterPois(newType)
    }
})

// 监听地图模式变化，自动处理热力图状态
watch([() => mapMode.value, () => mapType.value], ([newMode, newType]) => {
    // 巡检模式或3D模式下自动关闭热力图
    if (newMode === 'patrol' || newType === 'roadmap') {
        if (heatmapEnabled.value) {
            heatmapEnabled.value = false
        }
    }
})

// 监听热力图状态变化，控制POI显示/隐藏
watch(() => heatmapEnabled.value, (newEnabled) => {
    // 热力图状态变化时重新加载POI标记
    loadPoiMarkers()
})


// 监听点位数据变化
watch(() => amapPoiData.value, (newData) => {
    console.log('点位数据变化:', newData)
    loadPoiMarkers()
}, { deep: true })



// 生命周期
onMounted(() => {
    setTimeout(() => {
        // 等待高德地图API加载完成
        if (window.AMap) {
            initAmapMap()
        } else {
            const checkAMap = setInterval(() => {
                if (window.AMap) {
                    clearInterval(checkAMap)
                    initAmapMap()
                }
            }, 100)
        }
    }, 2000)

    // 模拟实时数据更新
    setInterval(() => {
        stats.value.totalVisitors += Math.floor(Math.random() * 10 - 5)
        if (stats.value.totalVisitors < 2400) stats.value.totalVisitors = 2400
        if (stats.value.totalVisitors > 2800) stats.value.totalVisitors = 2800
    }, 8000)
})
const selectClick = () => {
    scenicAreaCfg.isSelectOpen = !scenicAreaCfg.isSelectOpen
}
const handleCustomSelect = (item) => {

    scenicAreaCfg.value = item.id
    scenicAreaCfg.isSelectOpen = false

    // 根据当前模式选择对应的默认状态
    if (mapType.value == 'satellite') {
        // 转换坐标并重置视角
        const centerCoordinates = wgs84ToGcj02(item.position[0], item.position[1])
        map.value.setZoomAndCenter(item.zoom, centerCoordinates, false, 300)
    } else {
        const mapData = scenicAreaCfg.opts.find(v => v.id == scenicAreaCfg.value)
        nextTick(() => {
            cesiumMapRef.value.changeMap(mapData)
        })
    }

}

onUnmounted(() => {
    if (map.value) {
        map.value.destroy()
    }

    // 确保恢复页面滚动
    document.body.style.overflow = ''
})
</script>

<style scoped>
.amap-container {
    width: 100%;
    height: 100%;
    position: relative;
}

.amap-view {
    width: 100%;
    height: 100%;
    background: #000;
    /* 确保地图容器有暗色背景 */
}

/* 地图控制面板 */
.map-controls {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 100;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.view-controls {
    display: flex;
    gap: 10px;
    background: rgba(0, 0, 0, 0.8);
    border-radius: 12px;
    padding: 10px;
    backdrop-filter: blur(10px);
}

.control-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    padding: 8px 12px;
    background: rgba(0, 255, 136, 0.1);
    border: 1px solid rgba(0, 255, 136, 0.3);
    border-radius: 8px;
    color: #00ff88;
    cursor: pointer;
    transition: all 0.3s ease;
    min-width: 60px;
}

.control-btn:hover,
.control-btn.active {
    background: rgba(0, 255, 136, 0.2);
    border-color: #00ff88;
    box-shadow: 0 0 15px rgba(0, 255, 136, 0.3);
}

.control-btn.disabled {
    opacity: 0.4;
    cursor: not-allowed;
    background: rgba(128, 128, 128, 0.1) !important;
    border-color: rgba(128, 128, 128, 0.3) !important;
    color: #666 !important;
    box-shadow: none !important;
}

.control-btn svg {
    width: 18px;
    height: 18px;
}

.control-btn span {
    font-size: 0.75rem;
    font-weight: 500;
}

/* POI筛选面板 */
.poi-filter {
    background: rgba(0, 0, 0, 0.8);
    border-radius: 12px;
    padding: 15px;
    backdrop-filter: blur(10px);
    min-width: 200px;
}

.poi-filter h4 {
    color: #00ff88;
    margin: 0 0 10px 0;
    font-size: 0.9rem;
    text-align: center;
}

.filter-buttons {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.filter-btn {
    padding: 6px 10px;
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 6px;
    color: white;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.8rem;
    text-align: left;
}

.filter-btn:hover,
.filter-btn.active {
    background: rgba(0, 255, 136, 0.2);
    border-color: #00ff88;
    color: #00ff88;
}

/* 统计面板 */
.stats-panel {
    position: absolute;
    top: 20px;
    right: 20px;
    display: flex;
    gap: 15px;
    z-index: 100;
    transition: top 0.3s ease;
}

/* 巡检模式下调整统计面板位置 */
.stats-panel.patrol-mode {
    top: 120px;
    /* 适当向下移动，确保在视口内且避免重叠 */
}

.stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    background: rgba(0, 0, 0, 0.8);
    border: 1px solid rgba(0, 255, 136, 0.3);
    border-radius: 10px;
    padding: 12px 16px;
    backdrop-filter: blur(10px);
    min-width: 80px;
}

.stat-value {
    font-size: 1.4rem;
    font-weight: bold;
    color: #00ff88;
    text-shadow: 0 0 10px rgba(0, 255, 136, 0.5);
}

.stat-label {
    font-size: 0.75rem;
    color: rgba(255, 255, 255, 0.8);
    text-align: center;
}

/* POI详情面板 */
.poi-detail-panel {
    background: rgba(0, 0, 0, 0.95);
    border: 1px solid rgba(0, 255, 136, 0.3);
    border-radius: 12px;
    padding: 0;
    backdrop-filter: blur(15px);
    min-width: 300px;
    max-width: 400px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 255, 136, 0.1);
}

.detail-header h3 {
    margin: 0;
    color: #00ff88;
    font-size: 1.1rem;
}

.close-btn {
    background: none;
    border: none;
    color: #ffffff;
    font-size: 1.5rem;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background 0.3s ease;
}

.close-btn:hover {
    background: rgba(255, 255, 255, 0.1);
}

.detail-content {
    padding: 20px;
}

.poi-info .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    align-items: center;
}

.poi-info .label {
    color: rgba(255, 255, 255, 0.7);
    font-size: 0.9rem;
}

.poi-info .value {
    color: white;
    font-weight: 500;
    font-size: 0.9rem;
}

.poi-info .value.active {
    color: #66bb6a;
}

.poi-info .value.inactive {
    color: #ff6b6b;
}

.video-btn {
    margin-top: 10px;
    padding: 8px 16px;
    background: rgba(0, 255, 136, 0.2);
    border: 1px solid #00ff88;
    border-radius: 6px;
    color: #00ff88;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 0.8rem;
}

.video-btn:hover {
    background: rgba(0, 255, 136, 0.3);
}

.poi-description {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.poi-description p {
    margin: 0;
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.85rem;
    line-height: 1.4;
}

/* 监控视频弹窗样式 */
.monitor-video-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    box-sizing: border-box;
    margin: 0;
    transform: none;
}

.video-modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    backdrop-filter: blur(5px);
    z-index: 1;
}

.video-modal-content {
    position: relative;
    background: rgba(0, 0, 0, 0.95);
    border: 2px solid rgba(0, 255, 136, 0.5);
    border-radius: 16px;
    padding: 0;
    width: 700px;
    max-width: calc(100vw - 40px);
    max-height: calc(100vh - 40px);
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
    margin: 0;
    z-index: 10;
    flex-shrink: 0;
}

.video-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: rgba(0, 255, 136, 0.1);
    border-bottom: 1px solid rgba(0, 255, 136, 0.3);
}

.video-header h3 {
    margin: 0;
    color: #00ff88;
    font-size: 1.2rem;
}

.video-close-btn {
    background: none;
    border: none;
    color: #ffffff;
    font-size: 2rem;
    cursor: pointer;
    padding: 0;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.video-close-btn:hover {
    background: rgba(255, 255, 255, 0.1);
    color: #ff6b6b;
}

.video-container {
    width: 100%;
    background: #000;
    display: flex;
    justify-content: center;
    align-items: center;
}

.monitor-video {
    width: 100%;
    height: 360px;
    max-width: 100%;
    max-height: 50vh;
    background: #000;
    object-fit: contain;
}

.video-info {
    padding: 15px 20px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.video-info .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    align-items: center;
}

.video-info .label {
    color: rgba(255, 255, 255, 0.7);
    font-size: 0.9rem;
}

.video-info .value {
    color: white;
    font-weight: 500;
    font-size: 0.9rem;
}

/* 修改原有.scenic-select样式 */
.scenic-select {
    position: absolute;
    bottom: -60px;
    left: 0px;
    z-index: 1000;
    width: 120px;
    cursor: pointer;
    background: var(--glass-bg);
    border-radius: 6px;
    user-select: none;
    z-index: 9;
}

.selected-option {
    padding: 8px 16px;
    color: var(--primary-green);
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 3px;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    /* backdrop-filter: blur(5px); */
}

.arrow-icon {
    width: 16px;
    height: 16px;
    transition: transform 0.3s ease;
}

.scenic-select-options {
    position: absolute;
    bottom: 100%;
    left: 0;
    right: 0;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 6px;
    margin-top: 4px;
    backdrop-filter: blur(10px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.scenic-select-option {
    padding: 10px 16px;
    color: #fff;
    transition: all 0.3s ease;
}

.scenic-select-option:hover {
    background: rgba(0, 255, 136, 0.2);
}

.scenic-select-option.selected {
    background: rgba(0, 255, 136, 0.3);
    color: #fff;
    font-weight: 500;
}

/* 添加箭头动画 */
.scenic-select:not(.open) .arrow-icon {
    transform: rotate(0deg);
}

.scenic-select.open .arrow-icon {
    transform: rotate(180deg);
}

/* 响应式设计 */
@media screen and (max-width: 1400px) {
    .map-controls {
        top: 15px;
        left: 15px;
    }

    .poi-filter {
        min-width: 180px;
        padding: 12px;
    }

    .stats-panel {
        top: 15px;
        right: 15px;
        gap: 10px;
    }

    .stat-item {
        padding: 10px 12px;
        min-width: 70px;
    }

    .stat-value {
        font-size: 1.2rem;
    }

    .poi-detail-panel {
        min-width: 280px;
        max-width: 350px;
    }

    .video-modal-content {
        width: 600px;
    }

    .monitor-video {
        height: 270px;
    }
}

@media screen and (max-width: 768px) {
    .monitor-video-modal {
        padding: 10px;
    }

    .video-modal-content {
        width: 100%;
        max-width: calc(100vw - 20px);
        max-height: calc(100vh - 20px);
    }

    .monitor-video {
        height: auto;
        max-height: 40vh;
    }

    .video-header h3 {
        font-size: 1rem;
    }

    .video-info {
        padding: 12px 15px;
    }
}
</style>